package com.trust.walletcore.example.utils

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import wallet.core.jni.CoinType

object SolanaFaucet {
    private const val TAG = "SolanaFaucet"
    private val client = OkHttpClient()

    // 从 Solana DevNet 水龙头请求代币（1 SOL = 1_000_000_000 lamports）
    suspend fun requestTestSOL(address: String): String {
        return withContext(Dispatchers.IO) {
            try {
                // 1. 验证地址有效性
                if (!CoinType.SOLANA.validate(address)) {
                    return@withContext "地址无效：$address"
                }

                // 2. 构建 JSON-RPC 请求
                val jsonBody = """
                {
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "requestAirdrop",
                    "params": ["$address", 1000000000] // 请求 1 SOL
                }
                """.trimIndent()

                val request = Request.Builder()
                    .url(SolanaTransactionSender.solanaRpcUrl) // Solana DevNet 水龙头
                    .post(jsonBody.toRequestBody("application/json".toMediaType()))
                    .build()

                // 3. 发送请求
                val response = client.newCall(request).execute()
                val responseBody = response.body?.string() ?: return@withContext "请求失败：空响应"

                // 4. 解析结果
                val json = JSONObject(responseBody)
                if (json.has("error")) {
                    val error = json.getJSONObject("error")
                    "水龙头请求失败：${error.getString("message")}"
                } else {
                    val txId = json.getJSONObject("result").getString("value")
                    "成功领取 1 SOL！交易哈希：$txId"
                }
            } catch (e: Exception) {
                Log.e(TAG, "请求异常：${e.message}")
                "网络错误：${e.message}"
            }
        }
    }
}